package com.ruoyi.util.encrypt;

import java.util.LinkedHashSet;
import java.util.Random;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.Md5Crypt;

/**
 * @Description: md5加密 
 * @ClassName: Md5Util
 * @author syc
 * @date: 2022年9月19日 上午10:46:48
 */
public class Md5Util {

//	public static void main(String[] args) {
//		
//		String psd1 = "123456";
//	    System.out.println(DigestUtils.md5Hex(psd1));
//	    String psd2 = "123457";
//	    System.out.println(DigestUtils.md5Hex(psd2));
//	    
//		String pwd1 = "123456";
//	    //该方法盐值头必须加上"$1$",且仅支持8位以内的随机字符串
//	    System.out.println(Md5Crypt.md5Crypt(pwd1.getBytes(), "$1$salt"));
//	    System.out.println(Md5Crypt.md5Crypt(pwd1.getBytes(), "$1$salt"));
//
//	    System.out.println(Md5Crypt.md5Crypt(pwd1.getBytes(), "$1$sal"));
//
//	    //自定义工具类用于获取盐值
//	    String salt = getSalt(6);
//	    System.out.println("salt:"+salt);
//	    System.out.println(Md5Crypt.md5Crypt(pwd1.getBytes(), salt));
//	    salt = getSalt(6);
//	    System.out.println("salt:"+salt);
//	    System.out.println(Md5Crypt.md5Crypt(pwd1.getBytes(), salt));
//	}
//	
	
	 public static String getSalt(Integer size) {
	        return getSalt("$1$", size);
	    }
	    /**
	     * 获取计算随机数
	     * @param head  随机字符串自定义开头
	     * @param size  随机数长度
	     * @return
	     */
	    public static String getSalt(String head, Integer size) {
	        Random random = new Random();
	        String chs = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
	        int len = chs.length();
	        LinkedHashSet<Character> set = new LinkedHashSet<>();
	        //每一位字符不重复
	        while(set.size() < size) {
	            set.add(chs.charAt(random.nextInt(len)));
	        }
	        
	        for(Character c : set) {
	            head += c;
	        }
	        return head;
	    }	
}
